import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:hm_show_flutter/event/login_event.dart';
import 'package:hm_show_flutter/utils/shared_preferences_util.dart';

var dio;

typedef void ChildContext(BuildContext context);

class HttpUtil {
  // 工厂模式
  static HttpUtil get instance => _getInstance();

  static HttpUtil _httpUtil;

  static HttpUtil _getInstance() {
    if (_httpUtil == null) {
      _httpUtil = HttpUtil();
    }
    return _httpUtil;
  }

  HttpUtil() {
    BaseOptions options = BaseOptions(
      connectTimeout: 5000,
      receiveTimeout: 5000,
    );
    dio = new Dio(options);
    dio.interceptors
        .add(InterceptorsWrapper(onRequest: (RequestOptions options) async {
      print("App http interceptor =============请求数据=============");
      print("App http interceptor url=${options.uri.toString()}");
      print("App http interceptor params=${options.data}");
      dio.lock();

      Map<String, dynamic> header = new FormData.from({
        "app-type": Platform.isAndroid?0:1,
      });
      options.headers.addAll(header);

      await SharedPreferencesUtils.getToken().then((token) {
//        options.headers[Strings.token] = token;
        if (token != null) {
          print("App http interceptor Token：" + token);
          Map<String, dynamic> params = new FormData.from({
            "token": token,
          });
          options.queryParameters.addAll(params);
        }
      });
      await SharedPreferencesUtils.getCompany().then((company) {
        //获取门店id
        if (company != null && company.id != null) {
          print("App http interceptor CompanyId：" + company.id.toString());
          Map<String, dynamic> params = new FormData.from({
            "companyId": company.id,
          });
          options.queryParameters.addAll(params);
        }
      });

      dio.unlock();
      return options;
    }, onResponse: (Response response) {
      print("App http interceptor =============响应数据=============");
      print("App http interceptor code=${response.statusCode}");
      print("App http interceptor response=${response.data}");
      if (response.data['errno'] == 501) {
        loginEventBus.fire(LoginEvent(false));
      }
    }, onError: (DioError error) {
      print("App http interceptor =============请求错误=============");
      print("App http interceptor message =${error.message}");
    }));
  }

  Future get(String url,
      {Map<String, dynamic> parameters, Options options}) async {
    Response response;
    if (parameters != null && options != null) {
      response =
          await dio.get(url, queryParameters: parameters, options: options);
    } else if (parameters != null && options == null) {
      response = await dio.get(url, queryParameters: parameters);
    } else if (parameters == null && options != null) {
      response = await dio.get(url, options: options);
    } else {
      response = await dio.get(url);
    }
    return response.data;
  }

  Future post(String url,
      {Map<String, dynamic> parameters, Options options}) async {
    Response response;
    if (parameters != null && options != null) {
      response = await dio.post(url, data: parameters, options: options);
    } else if (parameters != null && options == null) {
      response = await dio.post(url, data: parameters);
    } else if (parameters == null && options != null) {
      response = await dio.post(url, options: options);
    } else {
      response = await dio.post(url);
    }
    return response.data;
  }
}
